import { DEBUG } from '../constants/setting';
import toast from './toast';

export function inWechat() {
  // if (typeof WeixinJSBridge !== 'undefined') {
  //   return true;
  // }
  return /micromessenger/.test(navigator.userAgent.toLowerCase());
}

export function scan() {
  console.log('调用微信扫码');
  const promise = new Promise((resolve, reject) => {
    window.wx.ready(() => {
      window.wx.scanQRCode({
        needResult: 1,
        scanType: ['qrCode', 'barCode'],
        success: (res) => {
          const code = res.resultStr;
          resolve(code);
        },
        cancel: () => {
          reject(new Error('用户取消扫码'));
        },
      });
    });
  });
  return promise;
}

export function getLocation() {
  console.log('调用微信定位');
  const promise = new Promise((resolve, reject) => {
    if (!inWechat()) { // mock
      const geo = new AMap.Geolocation({
        enableHighAccuracy: true,
      });
      geo.getCurrentPosition();
      AMap.event.addListener(geo, 'complete', (data) => {
        console.log('定位结果', data);
        // this.city = data.addressComponent.province;
        resolve({
          latitude: data.position.lat,
          longitude: data.position.lng,
        });
      });
      AMap.event.addListener(geo, 'error', (data) => {
        const err = `定位失败${JSON.stringify(data)}`;
        toast(err);
        reject(new Error(err));
      });
    } else {
      window.wx.ready(() => {
        window.wx.getLocation({
          type: 'gcj02',
          success: (res) => {
            resolve(res);
          },
          fail: () => {
            reject(new Error('定位失败'));
          },
          cancel: () => {
            reject(new Error('用户取消'));
          },
        });
      });
    }
  });
  return promise;
}

export function pay(params) {
  console.log('微信支付参数:', params);
  const promise = new Promise((resolve, reject) => {
    function onBridgeReady() {
      if (window.WeixinJSBridge) {
        WeixinJSBridge.invoke(
          'getBrandWCPayRequest',
          params,
          (res) => {
            // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回    ok，但并不保证它绝对可靠。
            if (res.err_msg === 'get_brand_wcpay_request:ok') {
              resolve(res);
            } else if (res.err_msg === 'get_brand_wcpay_request:cancel') {
              // eslint-disable-next-line
              reject('用户取消支付');
            } else {
              if (DEBUG) {
                // eslint-disable-next-line
                alert(JSON.stringify(res));
              }
              reject(res);
            }
          },
        );
      }
    }
    if (typeof WeixinJSBridge === 'undefined') {
      if (document.addEventListener) {
        document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
      } else if (document.attachEvent) {
        document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
        document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
      }
    } else {
      onBridgeReady();
    }
  });
  return promise;
}

export function setTitle(title) {
  console.log('set title---', title);
  document.title = title;
  const i = document.createElement('iframe');
  i.src = '/favicon.ico';
  i.style.display = 'none';
  i.onload = () => {
    setTimeout(() => {
      i.remove();
    }, 9);
  };
  document.body.appendChild(i);
}

